<template>
	<view class="recycle_form-container">

		<u-form :error-type="['toast']" :model="form" ref="uForm">
			<view class="recycle-devices">
				<!-- 选择分类 -->
				<view @tap="handleClassifyPopup">
					<u-form-item prop="classify">
						<u-field v-model="classify" label="品牌分类" placeholder-style="#999999" placeholder="请选择品牌分类"
							:border-bottom="false" :field-style="{
					          fontSize: '28rpx',
					          color: '\#333333',
							  background:'\#ffffff'
					      }" disabled>
							<u-icon name="arrow-down" slot="right" color="#707070" size="28" />
						</u-field>
					</u-form-item>
				</view>


				<!-- 型号名称 -->
				<view @tap="onSelectModel">
					<u-form-item prop="devices" :border-bottom="false">
						<u-field v-model="model" label="型号名称" placeholder-style="#999999" placeholder="请选择型号名称"
							:border-bottom="false" :field-style="{
					          fontSize: '28rpx',
					          color: '\#333333',
							  background:'\#ffffff'
					      }" disabled>
							<u-icon name="arrow-down" slot="right" color="#707070" size="28" />
						</u-field>
					</u-form-item>
				</view>


				<!-- 设备规格 -->
				<template v-if="form.class_two">
					<!-- 设备规格选择 -->
					<block v-for="(item, index) in goodsParamsList" :key="item.id">
						<view class="devices-params">
							<view class="devices-params-title">{{ item.name }}</view>
							<view class="devices-params-content">
								<block v-for="(subItem, index) in item.item_list">
									<view class="devices-params-item" @tap="handleSelectParams(item.id, subItem.id)"
										:class="{'recycle-classify-item--active': subItem.id == form.params[form.devices][item.id]}">
										{{ subItem.spec_value_str }}
									</view>
								</block>
								<u-form-item prop="params" v-model="form.params[item.id]"></u-form-item>
							</view>
						</view>
					</block>
				</template>
			</view>

			<!-- 			<view class="recycle-meid" v-show="isMEID">
				<u-form-item prop="meid">
				    <u-field
				      label="MEID" 
					  type="input"
					  v-model="form.meid"
					  maxlength="20"
				      placeholder-style="#999999"
				      placeholder="请输入设备MEID" 
				      :border-bottom="false"
				      :field-style="{
				          fontSize: '28rpx',
				          color: '\#333333'
				      }"
				    />
				</u-form-item>
				<u-form-item prop="sn">
				    <u-field
				      label="序列号" 
					  type="input"
					  v-model="form.sn"
					  maxlength="20"
				      placeholder-style="#999999"
				      placeholder="请输入设备序列号" 
				      :border-bottom="false"
				      :field-style="{
				          fontSize: '28rpx',
				          color: '\#333333'
				      }"
				    />
				</u-form-item>
			</view> -->


			<!-- 备注说明 -->
			<view class="recycle-remark">
				<u-form-item :border-bottom="false">
					<view class="flex1">
						<view>备注说明<text class="muted ml10">(选填)</text></view>
						<u-field v-model="form.remark" type="textarea" height="160" label-width="0" :clearable="false"
							:border-bottom="false" maxlength="240" style="line-height: 1.2em;" :field-style="{background:'\#ffffff'}" />
					</view>
				</u-form-item>
			</view>


			<!-- 拍照凭证 -->
			<view class="recycle-picture">
				<!-- <u-form-item prop="picture"> -->
				<u-form-item :border-bottom="false">
					<view class="flex1">
						<view @tap="isShowPictureModal = true">
							<text>拍照凭证</text>
							<text class="muted ml10">(请上传图片凭证)</text>
							<u-icon class="ml10" name="question-circle" color="#999999" />
						</view>
						<u-upload ref="uUpload" width="162" height="162" :auto-upload="false" :custom-btn="true"
							:border-bottom="false" :show-progress="false" @on-remove="handlePictureRemove"
							@on-choose-complete="handlePictureUpload">
							<view slot="addBtn" class="recycle-picture-button--upload">
								<u-icon name="/static/images/icon_camera.png" width="54" />
								<view class="xs normal">上传图片</view>
							</view>
						</u-upload>
					</view>
				</u-form-item>
			</view>
		</u-form>

		<!-- Widget -->
		<view>
			<!-- 分类选择 弹出层 -->
			<u-popup mode="center" v-model="showClassPopup">
				<view class="recycle-classify">
					<!-- 品牌 -->
					<view v-show="showPopupType == 1">
						<view class="recycle-classify-title">
							<view class="flex1">品牌</view>
							<view @tap="showClassPopup = false">
								<u-icon class="popup-close" name="close" />
							</view>
						</view>
						<scroll-view scroll-y="true" style="height: 678rpx;">
							<view class="recycle-classify-content">
								<block v-for="(item, index) in oneClassifyList" :key="item.id">
									<view class="recycle-classify-item"
										:class="{'recycle-classify-item--active': item.name == form.class_one}"
										@tap="handleSelectClassOne(item)">
										<u-image width="54rpx" height="54rpx" border-radius="5px" :src="item.image" />
										<text class="nr ml10"
											style="display: block;width: calc(100% - 54rpx);">{{ item.name }}</text>
									</view>
								</block>
							</view>
						</scroll-view>
						<template v-if="!oneClassifyList.length">
							<view class="recycle-classify-content-empty">暂无品牌~</view>
						</template>
					</view>
					<!-- 分类 -->
					<view v-show="showPopupType == 2">
						<view class="recycle-classify-title">
							<view @tap="showPopupType = 1">
								<u-icon class="recycle-classify-return" name="arrow-leftward" />
							</view>
							<view class="flex1">分类</view>
							<view @tap="showClassPopup = false">
								<u-icon class="popup-close" name="close" />
							</view>
						</view>
						<scroll-view scroll-y="true" style="height: 678rpx;">
							<view class="recycle-classify-content">
								<block v-for="(item, index) in twoClassifyList" :key="item.id">
									<view class="recycle-classify-item"
										:class="{'recycle-classify-item--active': item.name == form.class_two}"
										@tap="handleSelectClassTwo(item)">
										<u-image width="54rpx" height="54rpx" border-radius="5px" :src="item.image" />
										<text class="nr ml10"
											style="display: block;width: calc(100% - 54rpx);">{{ item.name }}</text>
									</view>
								</block>
							</view>
						</scroll-view>
						<template v-if="!twoClassifyList.length">
							<view class="recycle-classify-content-empty">暂无分类~</view>
						</template>
					</view>
				</view>
			</u-popup>


			<!-- 型号选择 弹出层 -->
			<u-popup mode="center" v-model="showModelPopup">
				<view class="recycle-classify">
					<view class="recycle-classify-title">
						<view class="flex1">型号</view>
						<view @tap="showModelPopup = false">
							<u-icon class="popup-close" name="close" />
						</view>
					</view>
					<view class="row-between mb20">
						<u-search class="recycle-classify-search" v-model="form.search" shape="square"
							placeholder="搜索型号名称" />
						<view class="recycle-classify-search-text" @tap="onSearchModel">搜索</view>
					</view>
					<scroll-view scroll-y="true" style="height: 678rpx; overflow: hidden;">
						<view class="recycle-classify-content">
							<block v-for="(item, index) in goodsList" :key="item.id">
								<view class="recycle-classify-item"
									:class="{'recycle-classify-item--active': item.id == form.devices}"
									@tap="handleSelectDevice(item.id)">
									<text class="nr ml10">{{ item.name }}</text>
								</view>
							</block>
						</view>
					</scroll-view>
					<template v-if="!goodsList.length">
						<view class="recycle-classify-content-empty">暂无型号~</view>
					</template>
				</view>
			</u-popup>

			<!-- 拍照凭证说明 Tips -->
			<u-modal v-model="isShowPictureModal" title="上传图片说明" confirm-text="我知道了">
				<view class="recycle-picture-modal">
					<view>1. 型号、序列号、MEID</view>
					<view class="mt10">2. 手机外形</view>
					<view class="mt10">3. 手机损坏部分</view>
				</view>
			</u-modal>
		</view>

		<!-- Submit -->
		<view class="recycle-submit" @tap="onSubmit">马上估价</view>

	</view>
</template>


<script>
	import {
		getGoodsCategory,
		getGoodsParams,
		getSearchGoods
	} from '@/api/recycle.js'

	import {
		uploadFile
	} from '@/utils/tools.js';

	export default {
		data() {
			return {
				mode: 'recycle', // 换租 || 回收
				// 表单数据
				form: {
					class_one: '', // 一级分类
					class_oneID: '', // 一级分类ID
					class_two: '', // 二级分类
					class_twoID: '', // 二级分类ID
					remark: '', // 备注
					pictures: [], // 图片
					devices: '', // 设备型号
					params: {}, // 设备参数
					search: '', // 搜索内容
					meid: '', // MEID
					sn: '', // 序列号
				},
				isMEID: false, // 是否需要MEID的输入
				showClassPopup: false, // 弹出层 -> 分类
				showPopupType: 1, // 弹出层类型[一级分类 ｜ 二级分类]
				showModelPopup: false, // 弹出层 -> 型号
				oneClassifyList: [], // 一级分类列表
				twoClassifyList: [], // 二级分类列表
				goodsList: [], // 设备列表
				goodsParamsList: [], // 设备规格列表
				isShowPictureModal: false, // 拍照凭证说明 Tips
				// 表单验证
				rules: {
					classify: [{
						validator: () => this.classify ? true : false,
						message: '请选择品牌分类',
					}],
					devices: [{
						required: true,
						message: '请选择设备型号',
					}],
					params: [{
						validator: () => {
							const params = this.form.params[this.form.devices];
							let verify = true;
							for (const [key, value] of Object.entries(params)) {
								if (!value) verify = false
							}
							return verify;
						},
						message: '请完善设备信息'
					}],
					picture: [{
						validator: () => {
							const LEN = this.form.pictures.length;
							return LEN ? true : false;
						},
						message: '请上传图片凭证'
					}],
					meid: [{
						validator: () => {
							if (!this.isMEID) return true;
							return this.form.meid ? true : false;
						},
						message: '请输入设备MEID'
					}],
					sn: [{
						validator: () => {
							if (!this.isMEID) return true;
							return this.form.sn ? true : false;
						},
						message: '请输入设备序列号'
					}],
				}
			}
		},

		computed: {
			// 品牌分类
			classify() {
				const form = this.form;
				return `${form.class_one}${form.class_one ? ' - ' : ''}${form.class_two}`;
			},
			// 型号名称
			model() {
				const model = this.goodsList.find(item => item.id == this.form.devices) || {};
				return model.name || '';
			}
		},

		methods: {
			// 分类选择弹出层
			handleClassifyPopup() {
				console.log("Classify ...");
				this.showClassPopup = true;
				const mode = this.showPopupType;

				this.form.class_one ?
					this.showPopupType = 2 :
					this.showPopupType = 1;
			},

			// 选择分类一
			handleSelectClassOne(item) {
				this.form.class_oneID = item.id;
				this.goodsParamsList = [];
				this.isMEID = false;
				this.$set(this.form, 'class_one', item.name);
				getGoodsCategory({
					pid: item.id
				}).then(res => {
					if (res.code != 1) return;
					this.twoClassifyList = res.data;
				});
				// 清空分类二数据
				if (this.form.class_two) this.$set(this.form, 'class_two', '');
				this.showPopupType = 2;
			},

			// 选择分类二
			handleSelectClassTwo(item) {
				this.form.class_twoID = item.id;
				this.goodsParamsList = [];
				this.isMEID = false;
				this.$set(this.form, 'class_two', item.name);
				getGoodsCategory({
					cid: item.id
				}).then(res => {
					if (res.code != 1) return;
					this.goodsList = res.data || [];
					const params = {};
					this.goodsList.forEach(item => params[item.id] = {});
					this.$set(this.form, 'params', params);
				});
				this.showClassPopup = false;
			},

			// 点击选择型号名称
			onSelectModel() {
				if (!this.form.class_two) return uni.showToast({
					title: '请先选择品牌分类',
					icon: 'none'
				});
				this.showModelPopup = true;
			},

			// 点击搜索型号
			onSearchModel() {
				const form = this.form;
				getSearchGoods({
					cid: form.class_twoID,
					goods_name: form.search
				}).then(res => {
					if (res.code != 1) return;
					this.goodsList = res.data || [];
					const params = {};
					this.goodsList.forEach(item => params[item.id] = {});
					this.$set(this.form, 'params', params);
				});
			},

			// 选择型号
			handleSelectDevice(id) {
				this.isMEID = false;
				this.showModelPopup = false;
				this.$set(this.form, 'devices', id);
				getGoodsParams({
					re_id: id
				}).then(({
					code,
					data
				}) => {
					if (code != 1) return;
					this.goodsParamsList = data.goods_item;
					this.isMEID = !!(data.is_meid * 1);

					this.goodsParamsList.forEach(item => {
						this.$set(this.form.params[this.form.devices], item.id, '');
					});
				});
			},

			// 选择设备规格
			handleSelectParams(key, value) {
				this.$set(this.form.params[this.form.devices], key, value);
			},

			// 图片上传
			handlePictureUpload(lists, index) {
				console.log(lists);
				uni.showLoading({
					title: '正在上传中...',
					mask: true
				});

				const len = lists.length;
				const count = this.form.pictures.length;
				for (let i = count; i < len; ++i) {
					const file = {
						...lists[i]
					};

					try {
						uploadFile(file.url).then(res => {
							uni.hideLoading();
							this.form.pictures.push(res.url);
						}).catch(err => {
							uni.hideLoading();
							this.$toast(err.msg || "上传失败");
						});
					} catch (e) {
						uni.hideLoading();
						this.$toast({
							title: "上传失败"
						});
					}
				}
			},

			// 图片删除
			handlePictureRemove(index, lists, name) {
				this.form.pictures.splice(index, 1);
			},

			// 表单提交
			onSubmit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						const form = this.form;
						const params = (list => {
							const params = [];
							for (const [key, value] of Object.entries(list)) params.push(value);
							return params;
						})(form.params[form.devices]);

						const field = {
							re_id: form.devices,
							item_ids: params,
							remarks: form.remark,
							images: form.pictures,
							// meid: form.meid,
							// serial_number: form.sn
							is_meid: this.isMEID
						}

						uni.navigateTo({
							url: '/bundle/pages/recycle_price/recycle_price' +
								'?order=' + JSON.stringify(field) +
								'&mode=' + this.mode
						});
					} else {
						console.log('验证失败');
					}
				});
			},
		},

		onLoad(options) {
			this.mode = options.mode || 'recycle';
			// 一级分类
			getGoodsCategory().then(res => {
				if (res.code != 1) return;
				this.oneClassifyList = res.data;
			});
		},

		onReady() {
			// 表单检验
			this.$refs.uForm.setRules(this.rules);
		}
	}
</script>


<style scoped>
	.recycle_form-container {
		padding: 20rpx;
	}

	.recycle_form-container>>>.u-field {
		padding: 0;
		flex: 1;
	}

	.recycle-devices,
	.recycle-remark,
	.recycle-picture,
	.recycle-meid {
		padding: 0 20rpx;
		border-radius: 10px;
		background-color: #FFFFFF;
	}

	.recycle-remark,
	.recycle-picture,
	.recycle-meid {
		margin-top: 20rpx;
	}

	.recycle-picture-button--upload {
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 162rpx;
		height: 162rpx;
		border: 2rpx dashed #CCCCCC;
		border-radius: 5px;
	}

	.recycle-classify {
		position: relative;
		width: 640rpx;
		/* height: 840rpx; */
		padding: 30rpx;
		border-radius: 10px;
		background-color: #FFFFFF;
	}

	.recycle-classify-title {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 40rpx;
		text-align: center;
		font-size: 34rpx;
		color: #333333;
	}

	.recycle-classify-search {
		flex: 1;
	}

	.recycle-classify-search-text {
		padding-left: 20rpx;
	}

	.recycle-classify-search>>>.u-search {
		padding: unset;
	}

	.recycle-classify-return {
		position: absolute;
		left: 0;
		top: 50%;
		transform: translateY(-50%);
		padding-right: 50rpx;
	}

	.recycle-classify-content {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}

	.recycle-classify-content-empty {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		font-size: 32rpx;
		color: #999999;
	}

	.recycle-classify-item {
		display: flex;
		align-items: center;
		width: 280rpx;
		height: 88rpx;
		padding: 0 20rpx;
		margin-bottom: 30rpx;
		background-color: #F2F2F2;
	}

	.recycle-classify-item--active {
		color: #24A3FF !important;
		background-color: #E8F6FF !important;
	}

	.devices-params {
		padding: 20rpx 0 0 0;
	}

	.devices-params-title {
		font-size: 30rpx;
		color: #333333;
		padding-bottom: 20rpx;
	}

	.devices-params-content {
		display: flex;
		flex-wrap: wrap;
	}

	.devices-params-item {
		padding: 8rpx 40rpx;
		margin-left: 18rpx;
		margin-bottom: 20rpx;
		border-radius: 2px;
		font-size: 28rpx;
		color: #333333;
		background-color: #F2F2F2;
	}

	.devices-params-item--active {
		color: #24A3FF;
		background-color: #E8F6FF;
	}

	.recycle-picture-modal {
		padding: 30rpx 40rpx;
		font-size: 28rpx;
		color: #333333;
	}

	.recycle-submit {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 88rpx;
		border-radius: 50px;
		margin-top: 40rpx;
		font-size: 34rpx;
		color: #FFFFFF;
		background-image: linear-gradient(to right, #3187FD, #24A3FF);
	}
</style>